package com.foosun.action;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.foosun.service.WeixinService;
import com.foosun.service.exception.AesException;
import com.foosun.util.demo.XMLParse;
import com.foosun.util.wechat.SignUtil;

@Controller
public class WeixinAction {
	@RequestMapping("/index.htm")
	public String index(){
		return "index";
	}
	
	@RequestMapping("/service.htm")
	public String service(@RequestParam("msg_signature") String signature,
			@RequestParam("timestamp") String timestamp,
			@RequestParam("nonce") String nonce,
			@RequestParam("echostr") String echostr, HttpServletResponse response) {
		
		String echoStr; //需要返回的明文
		try{
			response.setContentType("text/html");
			PrintWriter writer = response.getWriter();
			
			echoStr = SignUtil.verifyURL(signature, timestamp, nonce, echostr);
			System.out.println("verifyurl echostr: " + echoStr);
			writer.print(echoStr);  
			writer.close();
			writer = null;
		}catch(Exception ex){
			ex.printStackTrace();
		}
		return null;
	}
	
	@RequestMapping(value = "/service.htm",  method = RequestMethod.POST)
	public void receive(@RequestParam("msg_signature") String signature,
			@RequestParam("timestamp") String timestamp,
			@RequestParam("nonce") String nonce, 
			HttpServletRequest request, HttpServletResponse response) {
		try{
			// 将请求、响应的编码均设置为UTF-8（防止中文乱码）  
	        response.setCharacterEncoding("UTF-8");  
	        
			// 提取密文
			StringBuffer data = new StringBuffer();
			String line = null;
			InputStream is = request.getInputStream();
			BufferedReader reader = new BufferedReader(new InputStreamReader(is,"UTF-8"));
			while ((line = reader.readLine()) != null) {
				data.append(line);
			}
			
	        // 响应消息  
	        PrintWriter out = response.getWriter();			
	        Object[] encrypt = XMLParse.extract(data.toString());
	        String respContent = "";
			if(encrypt.length > 0) {
				if(SignUtil.verifySignature(signature, timestamp, nonce, encrypt[1].toString())){
					// 调用核心业务类接收消息、处理消息  
					respContent = WeixinService.processRequest(encrypt[1].toString());
				}
				
				String respMessage = SignUtil.encryptMsg(respContent, timestamp, nonce);
				System.out.println("after encrypt sEncrytMsg: " + respMessage);
				// 加密成功
		        out.print(respMessage); 				
			}
 
	        out.close();  
		}catch(IOException ex){
			ex.printStackTrace();
			//TODO Handle all the wechat error message here.
		}catch(AesException ex) {
			ex.printStackTrace();
		}
	}
	
}
